package com.smxy.mall.config;

import com.smxy.mall.annotation.JwtIgnore;
import com.smxy.mall.common.CustomException;
import com.smxy.mall.common.Response;
import com.smxy.mall.model.Audience;
import com.smxy.mall.model.Current;
import com.smxy.mall.utils.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.util.StringUtils;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * token拦截器
 */
@Slf4j
public class JwtInterceptor extends HandlerInterceptorAdapter{

    @Autowired
    private Audience audience;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");

        // 忽略带JwtIgnore注解的请求, 不做后续token认证校验
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            JwtIgnore jwtIgnore = handlerMethod.getMethodAnnotation(JwtIgnore.class);
            if (jwtIgnore != null) {
                return true;
            }
        }

        if (HttpMethod.OPTIONS.equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        // 获取请求头信息authorization信息
        final String authHeader = request.getHeader(JwtTokenUtil.AUTH_HEADER_KEY);
        log.info("## authHeader= {}", authHeader);

        if (StringUtils.isEmpty(authHeader)) {
            log.info("### 用户未登录，请先登录 ###");
            response.setStatus(401);
            throw new CustomException(Response.fail("401","用户未登录，请先登录"));
        }

        // 获取token
       // final String token = authHeader.substring(7);

        if(audience == null){
            BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
            audience = (Audience) factory.getBean("audience");
        }

//        // 验证token是否有效--无效已做异常抛出，由全局异常处理后返回对应信息
//        Claims claims = JwtTokenUtil.parseJWT(authHeader, audience.getBase64Secret());
//        System.out.println(claims);
        /**
         * 获取token中的用户信息
         */
        Current currentCurrent = JwtTokenUtil.getCurrentUser(authHeader,audience.getBase64Secret());
        System.out.println("----------------JwtInterceptor currentUser-----------------");
        System.out.println(currentCurrent);
        if(!StringUtils.isEmpty(currentCurrent.getUserId())){
            request.getSession().setAttribute("currentUser", currentCurrent);
            return true;
        }else{
            response.setStatus(401);
            throw new CustomException("401","登录失效");
        }
    }

}

